//
//  UIView+Extension.swift
//  AmountBody
//
//  Created by Qiu Jishuai on 2018/1/25.
//  Copyright © 2018年 RCMTM. All rights reserved.
//

import UIKit
import SnapKit
import pop

extension Int {
    var insets: UIEdgeInsets {
        let spacing = CGFloat(self)
        return UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
    }
}

extension UIView {
    class func instanteFormNib<T: UIView>() -> T {
        let name = String(describing: T.self)
        let view = UINib(nibName: name, bundle: nil).instantiate(withOwner: nil, options: nil).last
        return view as! T
    }
}

extension UIView {
    var anchorPoint: CGPoint {
        get {
            return layer.anchorPoint
        }
        set {
            let oldFrame = self.frame
            layer.anchorPoint = newValue
            self.frame = oldFrame
        }
    }
}

//
//extension UIView {
//    public var height: CGFloat {
//        get {
//            return frame.size.height
//        }
//        set {
//            frame.size.height = newValue
//        }
//    }
//    public var size: CGSize {
//        get {
//            return frame.size
//        }
//        set {
//            width = newValue.width
//            height = newValue.height
//        }
//    }
//    public var width: CGFloat {
//        get {
//            return frame.size.width
//        }
//        set {
//            frame.size.width = newValue
//        }
//    }
//
//    // swiftlint:disable identifier_name
//    public var x: CGFloat {
//        get {
//            return frame.origin.x
//        }
//        set {
//            frame.origin.x = newValue
//        }
//    }
//
//    public var y: CGFloat {
//        get {
//            return frame.origin.y
//        }
//        set {
//            frame.origin.y = newValue
//
//        }
//    }
//    // swiftlint:enable identifier_name
//}

extension UIView {
    @IBInspectable public var borderColor: UIColor? {
        get {
            guard let color = layer.borderColor else {
                return nil
            }
            return UIColor(cgColor: color)
        }
        set {
            guard let color = newValue else {
                layer.borderColor = nil
                return
            }
            layer.borderColor = color.cgColor
        }
    }

    @IBInspectable  var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }

    @IBInspectable public var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.masksToBounds = true
            layer.cornerRadius = abs(CGFloat(Int(newValue * 100)) / 100)
        }
    }
}


extension UIView {

    enum LinePosition {
        case top
        case left
        case bottom
        case right
    }

    ///添加分割线
    @discardableResult
    func addLine(on position: LinePosition,
                 color: UIColor = UIColor.lightGray,
                 lineWidth: CGFloat = 1 / UIScreen.main.scale,
                 inset: UIEdgeInsets = UIEdgeInsets.zero) -> UIView {
        let line = UIView()
        line.backgroundColor = color
        addSubview(line)
        line.snp.makeConstraints{
            switch position {
            case .top:
                $0.left.equalToSuperview().offset(inset.left)
                $0.right.equalToSuperview().offset(-inset.right)
                $0.top.equalToSuperview().offset(inset.top)
                $0.height.equalTo(lineWidth)
            case .left:
                $0.left.equalToSuperview().offset(inset.left)
                $0.top.equalToSuperview().offset(inset.top)
                $0.bottom.equalToSuperview().offset(-inset.bottom)
                $0.width.equalTo(lineWidth)
            case .bottom:
                $0.left.equalToSuperview().offset(inset.left)
                $0.right.equalToSuperview().offset(-inset.right)
                $0.bottom.equalToSuperview().offset(-inset.bottom)
                $0.height.equalTo(lineWidth)
            case .right:
                $0.right.equalToSuperview().offset(-inset.right)
                $0.top.equalToSuperview().offset(inset.top)
                $0.bottom.equalToSuperview().offset(-inset.bottom)
                $0.width.equalTo(lineWidth)
            }
        }
        return line
    }

    //设置UI规范的圆角
    func setThemeRoundedBorder() {
        setRoundedBorder(withCornerRadius: 8,
                         borderColor: UIColor.gray,
                         borderWidth: 1 / UIScreen.main.scale)
    }

    ///设置圆角
    func setRoundedBorder(withCornerRadius cornerRadius: CGFloat = 0,
                          borderColor: UIColor = UIColor.white,
                          borderWidth: CGFloat = 0,
                          layerFrame: CGRect = CGRect.zero,
                          shouldRasterize: Bool = false,
                          useNewLayer: Bool = false) {
        let layer: CALayer
        if useNewLayer {
            layer = CALayer()
            var borderFrame = layerFrame
            if layerFrame == CGRect.zero {
                borderFrame = self.bounds
            }
            layer.frame = borderFrame
        } else {
            layer = self.layer
        }
        layer.cornerRadius = (cornerRadius == 0) ? layer.frame.width / 2 : cornerRadius
        layer.borderWidth = borderWidth
        layer.masksToBounds = true
        layer.borderColor = borderColor.cgColor
        if shouldRasterize {
            layer.shouldRasterize = shouldRasterize
            layer.rasterizationScale = UIScreen.main.scale
        }
        if useNewLayer {
            self.layer.addSublayer(layer)
        }
    }
}

extension UIView {
    
    enum Position {
        case leftTop
        case leftBottom
        case rightTop
        case rightBottom
        
    }
    
    enum PopAnimationType {
        case scaleX
        case scaleY
        case scaleXY
        
        case rotation
        case rotationX
        case rotationY
        
        case translationX
        case translationXY
        case translationY
        case translationZ
        
        var property: String {
            switch self {
            case .scaleX: return kPOPViewScaleX
            case .scaleY: return kPOPViewScaleY
            case .scaleXY: return kPOPViewScaleXY
            case .rotation: return kPOPLayerRotation
            case .rotationX: return kPOPLayerRotationX
            case .rotationY: return kPOPLayerRotationY
            case .translationX: return kPOPLayerTranslationX
            case .translationY: return kPOPLayerTranslationY
            case .translationXY: return kPOPLayerTranslationXY
            case .translationZ: return kPOPLayerTranslationZ
            }
        }
    }
    
    enum PopTimingFunctionType {
        case linear
        case easeIn
        case easeInEaseOut
        case easeOut
        case custom(String)
        var function: String {
            switch self { //kCAAnimationLinear
            case .linear:
                return kCAMediaTimingFunctionLinear   // 匀速
            case .easeInEaseOut:
                return kCAMediaTimingFunctionEaseInEaseOut // 先慢后快再慢
            case .easeIn:
                return kCAMediaTimingFunctionEaseIn  //  先慢后快
            case .easeOut:
                return kCAMediaTimingFunctionEaseOut //  先快后慢
            case .custom(let function):
                return function
            }
        }
    }
    
    @discardableResult
    func addBasicAnimation(with type: PopAnimationType,
                           duration: TimeInterval = 1,
                           fromValue: Any? = nil,
                           toValue: Any,
                           timingFunction: PopTimingFunctionType = .linear,
                           repeatCount: Int = 0,
                           repeatForever: Bool = true,
                           beginTime: CFTimeInterval = 0,
                           autoreverses: Bool = false,
                           key: String? = nil,
                           advanceBlock: ((UIView) -> Void)? = nil,
                           completionBlock: ((POPBasicAnimation, Bool) -> Void)? = nil) -> Self {
        advanceBlock?(self)
        let animation = POPBasicAnimation(propertyNamed: type.property)!
        animation.duration = duration
        animation.repeatForever = repeatForever
        animation.fromValue = fromValue
        animation.toValue = toValue
        animation.repeatCount = repeatCount
        animation.autoreverses = autoreverses
        animation.timingFunction = CAMediaTimingFunction(name:timingFunction.function)
        animation.beginTime = beginTime == 0 ? 0 : CACurrentMediaTime() + beginTime
        if let completionBlock = completionBlock {
            animation.completionBlock = { (anim, finish) in
                completionBlock(anim as! POPBasicAnimation, finish)
            }
        }
        
        switch type {
        case .scaleX, .scaleY, .scaleXY:
            pop_add(animation, forKey: key)
        default: layer.pop_add(animation, forKey: key)
        }
        return self
    }
}
